
import { searchPlugsGoodsSpecificationByGoodsId, insertPlugsShopCart, getPlugsShopCartByUserId } from "@/tools/request/api.js"
import JSONBig from 'json-bigint';
 
 


export default {
	namespaced: true,
	state: () => ({
		totalCartNum: 0,
		totalCartList: []
	}),
	mutations: {
		
		// 设置购物车数据
		SET_CART_DATA (state, value) {
			let nums = 0;
			let avalibleList = value.filter((item) => {
				return item.status == 0;
			})
			avalibleList.forEach((item) => {
				nums += item.goodsNum;
			});
			state.totalCartNum = nums;
			state.totalCartList = avalibleList;
		}
	},
	actions: {
		// 获取购物车商品列表
		async getShopCartList({commit, rootState}) {
			let postdata = {
				page: 1,
				size: 200,
				businessId: rootState.business_store.businessId,
				userServiceToken: rootState.app_store.userServiceToken
			}
			let res = await getPlugsShopCartByUserId(postdata);
			if (res.code != 200) return uni.$showMsg();
			let list = res.body.list;
			commit('SET_CART_DATA', list);
			uni.stopPullDownRefresh();
		},
		// 点击加入购物车图标时，默认将第一个规格加入购物车
		async addCartGoods ({commit, dispatch, rootState}, good) {
			rootState.loading_store.loadingShow = true;
			let specRes = await searchPlugsGoodsSpecificationByGoodsId({goodsId: good.id});
			if (specRes.code != 200) return uni.$showMsg();
			let spec_list = specRes.body.plugsGoodsSpecificationList;
			let spec_id = '';
			if (spec_list.length) {
				spec_id = spec_list[0].id;
			}
			let postData = {
				goodsId: good.id,
				goodsCategoryId: good.categoryId.toString(),
				goodsNum: 1,
				goodsSpecificationIds: spec_id,
				businessId: rootState.business_store.businessId
			};
			insertPlugsShopCart(postData).then(res => {
				rootState.loading_store.loadingShow = false;
				if (res.code == 200) {
					uni.$showMsg('加入成功！')
					dispatch('getShopCartList');
				} else {
					uni.showToast({
						title: '加入失败！',
						duration: 1000,
						icon: 'error'
					})
				}
			})
		},
	},
	getters: {},
}
